package com.tacc.tyun.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.tacc.tyun.base.BaseConstant;
import com.tacc.tyun.model.MsgBanner;
import com.tacc.tyun.model.SysConfig;
import com.tacc.tyun.model.info.MsgBannerInfo;
import com.tacc.tyun.model.info.ReturnInfo;
import com.tacc.tyun.service.BaseMenuService;
import com.tacc.tyun.service.MsgBannerService;
import com.tacc.tyun.service.SysConfigService;
import com.tacc.tyun.util.BaseUtil;
import com.tacc.tyun.util.ConfigConstant;
import com.tacc.tyun.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.*;

/**
*
* @author congcong tao
* @date 2017/8/21 15:25
*/
@Controller
@RequestMapping("/msgBanner")
public class MsgBannerController extends BaseController{

    private static Logger LOGGER= LoggerFactory.getLogger(MsgBannerController.class);

    @Resource
    private MsgBannerService msgBannerService;
    @Resource
    private BaseMenuService baseMenuService;
    @Resource
    private SysConfigService sysConfigService;
    private MsgBanner msgBanner;

    @RequestMapping("/listPage")
    public ModelAndView List(HttpServletRequest request, HttpServletResponse response, String menuid){
        return new ModelAndView("banner/msgBannerList").addObject("headTitle",acceptTitle(menuid,baseMenuService));
    }

    @RequestMapping(value = "/JsonList",method = RequestMethod.POST)
    public @ResponseBody
    JSONObject JsonList(HttpServletRequest request, MsgBanner msgBanner, PageInfo<MsgBanner> pageInfo) throws MalformedURLException, UnsupportedEncodingException {
        int pageNum=(pageInfo.getPageNum()/pageInfo.getPageSize())+1;
        pageInfo.setPageNum(pageNum);
        pageInfo=msgBannerService.pageInfo(msgBanner,pageInfo.getPageSize(),pageInfo.getPageNum());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for(MsgBanner item:pageInfo.getList()){
                row=new JSONObject();
                row.put("bannerId",item.getBannerId());
                row.put("imageTitle",item.getImageTitle());
                row.put("imageUrl",item.getImageUrl());
                row.put("status",item.getStatus());//1：启用作为首页轮播2：不启用
                row.put("createtime", DateUtil.DateToStr(item.getCreateTime(),DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("rows",rows);
        }
        return jsonObject;
    }

    //查看通知
    @RequestMapping(value = "/SelectEntity",method = RequestMethod.GET)
    public ModelAndView SelectEntity(String bannerId){
        ModelAndView mv=new ModelAndView("banner/msgBannerUpdateOrSave");
        if (StringUtils.isNotEmpty(bannerId)){
            MsgBanner msgBanner=(MsgBanner)msgBannerService.selectByPrimaryKey(bannerId);
            mv.addObject(msgBanner);
        }
        return mv;
    }

    @RequestMapping(value = "/UpdateOrAddEntity",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject UpdateOrAddEntity(MsgBannerInfo msgBannerInfo, HttpServletRequest request){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();

        if(StringUtils.isEmpty(msgBannerInfo.getBannerId())){
            msgBanner=new MsgBanner();
            msgBanner.setBannerId(BaseUtil.uId());
            msgBanner.setImageTitle(msgBannerInfo.getImageTitle());
            msgBanner.setImageDesc(msgBannerInfo.getImageDesc());
            msgBanner.setImageUrl(msgBannerInfo.getImageUrl());
            msgBanner.setBannerUrl(msgBannerInfo.getBannerUrl());

            msgBanner.setSort(msgBannerInfo.getSort());
            msgBanner.setStatus(BaseConstant.BANNER_NO);//新建是不启用的

            //msgBanner.setCreator(acceptUserName(request));
            msgBanner.setCreateTime(new Date());
            msgBanner.setUpdateTime(msgBanner.getCreateTime());
            msgBanner.setRemoveTag(BaseConstant.REMOVE_NO);

            int id=msgBannerService.insert(msgBanner);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_INSERT);
            }
        }else{
            msgBanner=new MsgBanner();
            msgBanner.setBannerId(msgBannerInfo.getBannerId());
            msgBanner.setImageTitle(msgBannerInfo.getImageTitle());
            msgBanner.setImageDesc(msgBannerInfo.getImageDesc());
            msgBanner.setImageUrl(msgBannerInfo.getImageUrl());
            msgBanner.setBannerUrl(msgBannerInfo.getBannerUrl());

            msgBanner.setUpdateTime(new Date());
            int id=msgBannerService.updateByPrimaryKey(msgBanner);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    /**
     * 根据ids批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/DeleteEntity",method = RequestMethod.DELETE)
    @ResponseBody
    public JSONObject deleteByIds(@RequestParam("ids")String[] ids){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(ids==null || ids.length<1){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else {
            int info=msgBannerService.deleteBannerByIds(ids,BaseConstant.REMOVE_YES);//
            if (info==-1){
                LOGGER.error("删除失败");
                returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    /**
     * 根据ids停用
     * @param ids
     * @return
     */
    @RequestMapping(value = "/stopEntity",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject stopByIds(@RequestParam("ids")String[] ids){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(ids==null || ids.length<1){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else {
            //判断最后一个字符
            List<String> dids=new ArrayList<String>();
            List<String> eids=new ArrayList<String>();
            for(String idt:ids){
                if (idt.contains(":")){
                    String[] split = idt.split(":");
                    if (StringUtils.isNotEmpty(split[1]) && StringUtils.equals("2",split[1])){//2是不启用
                        dids.add(split[0]);
                    }else{//当type为null时也默认为启用
                        eids.add(split[0]);
                    }
                }
            }
            if (dids!=null && dids.size()>0){
                int dinfo=msgBannerService.updateStatusByIds(dids,BaseConstant.BANNER_YES);//启用
                if (dinfo==-1){
                    LOGGER.error("启用失败");
                    returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
                }
            }
            if (eids!=null && eids.size()>0){
                int einfo=msgBannerService.updateStatusByIds(eids,BaseConstant.BANNER_NO);//停用
                if (einfo==-1){
                    LOGGER.error("停用失败");
                    returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
                }
            }

        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }


    /**
     * 排序
     * 每次排序都生成一个新的配置文件
     */
    @RequestMapping(value = "/sortEntity",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject sortByIds(@RequestParam("ids")String[] ids){
        String key= ConfigConstant.BANNER_CONFIG_KEY;
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(ids!=null && ids.length>0){
            List<Map<String,Integer>> mapList=new ArrayList<Map<String, Integer>>();
            int rank=1;
            for (String id:ids){
                Map<String,Integer> map=new HashMap<>();
                map.put("id",rank);
                mapList.add(map);
                rank++;
            }

            Gson gson = new Gson();
            String value= gson.toJson(mapList);
            //先查询总数
            int count=sysConfigService.selectCountLikeKey(key);
            key=key+(count+1);
            SysConfig sysConfig=new SysConfig();
            sysConfig.setKey(key);
            sysConfig.setValue(value);
            sysConfig.setCreatetime(new Date());
            sysConfig.setUpdatetime(sysConfig.getCreatetime());
            sysConfigService.insert(sysConfig);
            //int info=msgBannerService.updateSortEntity(ids);

        }else {
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

}
